package com.uphone.kingmall.activity;

import android.animation.ValueAnimator;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.china.zhuoyue.R;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.uphone.kingmall.activity.personal.OtherSettleActivity;
import com.uphone.kingmall.adapter.KanJiaJiLuListAdpater;
import com.uphone.kingmall.base.BaseActivity;
import com.uphone.kingmall.bean.GoodsDetailBean;
import com.uphone.kingmall.bean.HaggleDetailBean;
import com.uphone.kingmall.bean.HaggleRolesBean;
import com.uphone.kingmall.bean.OtherOderBean;
import com.uphone.kingmall.dialog.KanJiaGuiZeDialog;
import com.uphone.kingmall.listener.onNormalRequestListener;
import com.uphone.kingmall.login.LoginActivity;
import com.uphone.kingmall.utils.CommonUtil;
import com.uphone.kingmall.utils.ConstansUtils;
import com.uphone.kingmall.utils.GlideUtils;
import com.uphone.kingmall.utils.GsonUtils;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.OkGoUtils;
import com.uphone.kingmall.utils.SharedPreferencesHelper;
import com.uphone.kingmall.utils.TimeUtil;
import com.uphone.kingmall.utils.ToastUtils;
import com.uphone.kingmall.utils.intent.IntentData;
import com.uphone.kingmall.utils.intent.IntentUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * author : SuMeng
 * e-mail : 986335838@qq.com
 * time   : 2019/02/20
 * desc   : 我要砍价详情页面
 */
public class HaggleDetailActivity extends BaseActivity {
    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.iv_icon)
    ImageView ivIcon;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_guize)
    TextView tvGuize;
    @BindView(R.id.pb_process)
    ProgressBar pbProcess;
    @BindView(R.id.tv_yikan)
    TextView tvYikan;
    @BindView(R.id.tv_shengyu)
    TextView tvShengyu;
    @BindView(R.id.rv_jilu)
    RecyclerView rvJilu;
    @BindView(R.id.tv_share)
    TextView tvShare;
    @BindView(R.id.tv_over_time)
    TextView tvOverTime;
    @BindView(R.id.content_detail)
    LinearLayout contentDetail;

    @IntentData
    private int id = -1;
    private HaggleDetailBean.HaggleInfoBean haggleBean;
    private KanJiaJiLuListAdpater kanJiaJiLuListAdpater;
    private int endTime;
    private boolean isWeb = false;

    @Override
    public int getLayoutContentId() {
        return R.layout.kingmall_activity_kanjia;
    }

    @Override
    public void initView() {
        Intent mgetvalue = getIntent();
        String maction = mgetvalue.getAction();
        if (Intent.ACTION_VIEW.equals(maction)) {
            Uri uri = mgetvalue.getData();
            if (uri != null) {
                String webId = uri.getQueryParameter("id");
                if (!TextUtils.isEmpty(webId)) {
                    try {
                        id = Integer.parseInt(webId);
                        isWeb = true;
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        LogUtils.e("id:" + id);
        rvJilu.setLayoutManager(new LinearLayoutManager(HaggleDetailActivity.this));
        kanJiaJiLuListAdpater = new KanJiaJiLuListAdpater();
        rvJilu.setAdapter(kanJiaJiLuListAdpater);
    }

    @Override
    public void initData() {
        try {
            HttpParams params = new HttpParams();
            params.put("haggleId", id);
            OkGoUtils.progressRequest(MyUrl.haggleInfo, this, params, new onNormalRequestListener() {

                @Override
                public void onSuccess(String response, int code) {
                    HaggleDetailBean bean = GsonUtils.getGson().fromJson(response, HaggleDetailBean.class);
                    if (bean.getCode() == 0) {
                        haggleBean = bean.getHaggleInfo();
                        loadData();
                    }
                }

                @Override
                public void onError(Response<String> response) {

                }
            });
        } catch (Exception e) {
            LogUtils.e("异常:" + e.toString());
            e.printStackTrace();
        }
    }

    private void loadData() {
        if (haggleBean != null) {
            setAnimation(pbProcess, (int) (haggleBean.getHagglePrice() * 100 / haggleBean.getGoodsPrice()));
            tvName.setText(haggleBean.getGoodsName() + "");
            tvPrice.setText("价值" + haggleBean.getGoodsPrice() + "元");
            tvYikan.setText("已砍" + haggleBean.getHagglePrice() + "元");
            tvShengyu.setText("剩余" + haggleBean.getUnhagglePrice() + "元");
            if (haggleBean.getHaggleType() == 1) {
                //自己发起的砍价
                tvShare.setText("喊好友砍一刀");
                if (haggleBean.getUnhagglePrice() == 0) {
                    tvShare.setText("去支付");
                }
            } else {
                //他人发起的砍价
                tvShare.setText("帮他砍一刀");
            }
            endTime = haggleBean.getEndTime();
            daojishi();
            GlideUtils.getInstance().loadCornerImage(this, haggleBean.getGoodsMainImg(), SizeUtils.dp2px(2), ivIcon);
            kanJiaJiLuListAdpater.setNewData(haggleBean.getHaggleHelps());
        }
    }

    private void daojishi() {
        if (endTime <= 0) {
            tvOverTime.setText("已结束");
        } else {
            tvOverTime.setText("还剩 " + TimeUtil.secToTime(endTime) + " 结束");
            endTime--;
            handler.sendEmptyMessageDelayed(0, 1000);
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            daojishi();
        }
    };

    @OnClick({R.id.tv_back, R.id.tv_guize, R.id.tv_share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_back:
                onBackPressed();
                break;
            case R.id.tv_guize:
                shopRule();
                break;
            case R.id.tv_share:
                if (TextUtils.isEmpty(SharedPreferencesHelper.getToken())) {
                    CommonUtil.startIntent(HaggleDetailActivity.this, LoginActivity.class);
                    return;
                }
                if (haggleBean != null) {
                    if (haggleBean.getHaggleType() == 1) {
                        //自己发起的砍价
                        if (TextUtils.equals("去支付", tvShare.getText().toString().trim())) {
                            //支付
                            if (id != -1) {
                                HttpParams params = new HttpParams();
                                params.put("goodsId", haggleBean.getGoodsId());
                                OtherOderBean otherOderBean = new OtherOderBean("1", "0.0", new GoodsDetailBean.GoodsBean(haggleBean), new ArrayList<GoodsDetailBean.GoodsBean.PropsBean.PropBean>(),
                                        haggleBean.getInstallationFee());
                                IntentUtils.getInstance().with(HaggleDetailActivity.this, OtherSettleActivity.class)
                                        .putInt(ConstansUtils.ID, id)
                                        .putString(ConstansUtils.JSON_STR, GsonUtils.getGson().toJson(otherOderBean)).start();
                            }

                            return;
                        }
                        if (TextUtils.equals("已结束", tvOverTime.getText().toString().trim())) {
                            ToastUtils.showShortToast(HaggleDetailActivity.this, "活动已结束");
                            return;
                        }

                        showSharePop(contentDetail, "http://wechat.91wzsc.com/myBargainIndex/" + id + "?", haggleBean.getGoodsName(),
                                "好物价格由你定，帮我砍到0元购吧", haggleBean.getGoodsMainImg());
//                        DialogUtil.showShareDailog(HaggleDetailActivity.this, "您已砍价" + haggleBean.getHagglePrice() + "元", MyUrl.h5HaggleDetail + id, "我要砍价");
//                        KanJiaShareDialog kanJiaShareDialog = new KanJiaShareDialog(HaggleDetailActivity.this, "50");
//                        kanJiaShareDialog.show();
                    } else {
                        //他人发起的砍价
                        helpHaggle();
                    }
                }
                break;
        }
    }

    private void helpHaggle() {
        HttpParams params = new HttpParams();
        params.put("haggleId", id);
        OkGoUtils.progressRequest(MyUrl.helpHaggle, this, params, new onNormalRequestListener() {
            @Override
            public void onSuccess(String response, int code) {
                try {
                    if (code == 0) {
                        JSONObject jsonObject = new JSONObject(response);
                        String hagglePrice = jsonObject.getString("hagglePrice");
                        if (!TextUtils.isEmpty(hagglePrice)) {
                            ToastUtils.showShortToast(HaggleDetailActivity.this, "帮他砍了" + hagglePrice + "元");
                        }
                        // 重新加载数据
                        initData();
                    }
                } catch (Exception e) {
                    LogUtils.e("异常:" + e.toString());
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Response<String> response) {

            }
        });
    }

    private String rule = null;

    private void shopRule() {
        if (rule == null) {
            OkGoUtils.progressRequest(MyUrl.haggleRoles, this, null, new onNormalRequestListener() {
                @Override
                public void onSuccess(String response, int code) {
                    HaggleRolesBean bean = GsonUtils.getGson().fromJson(response, HaggleRolesBean.class);
                    if (bean.getCode() == 0) {
                        rule = "";
                        List<HaggleRolesBean.HaggleRoleBean> roleBeans = bean.getHaggleRole();
                        if (roleBeans != null) {
                            for (int i = 0; i < roleBeans.size(); i++) {
                                rule += roleBeans.get(i).getSortNum() + "." + roleBeans.get(i).getContent() + "\n";
                            }
                        }
                        showRuleDialog();
                    }
                }

                @Override
                public void onError(Response<String> response) {
                }
            });
        } else {
            showRuleDialog();
        }
    }

    private void showRuleDialog() {
        KanJiaGuiZeDialog kanJiaGuiZeDialog = new KanJiaGuiZeDialog(HaggleDetailActivity.this, rule);
        kanJiaGuiZeDialog.show();
    }

    private void setAnimation(final ProgressBar view, final int mProgressBar) {
        ValueAnimator animator = ValueAnimator.ofInt(0, mProgressBar).setDuration(3000);

        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                view.setProgress((int) valueAnimator.getAnimatedValue());
            }
        });
        animator.start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    /**
     * 返回处理，防止点击返回按钮的时候，会直接退出当前app
     **/
//    @Override
//    public void onBackPressed() {
//        //NavUtils.getParentActivityIntent()方法可z以获取到跳转至父Activity的Intent或者为null
//        //NavUtils.shouldUpRecreateTask() 返回true父Activity应该重新创建一个新的任务栈，返回false同样的任务栈应该被使用作为目标Intent
//        //isTaskRoot()用来判断该Activity是否为任务栈中的根Activity，即启动应用的第一个Activity
//        if (isWeb) {
//            Intent upIntent = NavUtils.getParentActivityIntent(this);
//            if (NavUtils.shouldUpRecreateTask(this, upIntent) || isTaskRoot()) {
//                //如果父Activity和当前Activity不在同一个Task中的，则需要借助TaskStackBuilder创建一个新的Task
//                TaskStackBuilder.create(this)
//                        .addNextIntentWithParentStack(upIntent)
//                        .startActivities();
//            } else {
//                //如果父Activity和当前Activity是在同一个Task中的，则直接调用navigateUpTo()方法进行跳转
//                upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                NavUtils.navigateUpTo(this, upIntent);
//            }
//        }
//        super.onBackPressed();
//    }
}
